package com.dunqi.gpm.cangxi.WeekReport.WeekPlan.WeekPlanDetail

import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast

import com.dunqi.gpm.cangxi.R
import com.dunqi.gpm.cangxi.WeekReport.Model.WeekPlan
import com.dunqi.gpm.cangxi.WeekReport.Model.Projects
import com.dunqi.gpm.cangxi.home.adapter.SpinnerAdapter
import com.dunqi.gpm.cangxi.home.bean.Page
import kotlinx.android.synthetic.main.fragment_week_plan_creat.*
import java.util.*
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import com.dunqi.gpm.cangxi.common.base.Data
import org.greenrobot.eventbus.EventBus
import kotlin.collections.ArrayList


class WeekPlanDetailFragment : Fragment(), DataModel.DataResult {
    override fun delete(data: Data<*>?) {
        if (data !== null && data.resultCode == 1) {
            Toast.makeText(activity, "删除成功!", Toast.LENGTH_SHORT).show()
            EventBus.getDefault().post("refresh_weekPlanList")
            activity!!.finish()
        }
        Toast.makeText(activity, "删除失败!", Toast.LENGTH_SHORT).show()
    }

    override fun success2(data: Data<*>?) {
        if (data !== null && data.resultCode == 1) {
            Toast.makeText(activity, "保存成功!", Toast.LENGTH_SHORT).show()
            EventBus.getDefault().post("refresh_weekPlanList")
            activity!!.finish()
        }
    }

    override fun fail(throwable: Throwable?) {

    }

    override fun success(data: Page<Projects>?) {
        if (data != null && data.size > 0) {
            mData = data.list
            var list = ArrayList<String?>()
            for (project in data.list) {
                list.add(project.getProjectName())
            }
            setMySpinner(list)
        } else {
            Toast.makeText(activity, "没有查询到可计划的项目!", Toast.LENGTH_SHORT).show()
        }
    }

    fun setMySpinner(list: ArrayList<String?>) {
        val toArray = list.toTypedArray()
        var adapter = SpinnerAdapter(activity!!, toArray)
        project_name.adapter = adapter
        project_name.onItemSelectedListener = object : OnItemSelectedListener {

            override fun onItemSelected(parent: AdapterView<*>, view: View,
                                        position: Int, id: Long) {
                projectName = project_name.getSelectedItem() as String
            }

            override fun onNothingSelected(parent: AdapterView<*>) {
            }
        }
    }


    var item: WeekPlan? = null
    private var mParam2: String? = null
    var dataModel: DataModel? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null) {
            item = arguments!!.getSerializable(ARG_PARAM1) as WeekPlan?
            mParam2 = arguments!!.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_week_plan_creat, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        fragment_week_plan_detail_title.setOnClickListenerOfRight { commit() }

        setCommon()
        if (item === null) {//创建
            creat()
        } else {//修改
            setView()
        }
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
    }

    override fun onDetach() {
        super.onDetach()
    }

    companion object {
        private val ARG_PARAM1 = "object"
        private val ARG_PARAM2 = "param2"

        fun newInstance(param1: WeekPlan?, param2: String): WeekPlanDetailFragment {
            val fragment = WeekPlanDetailFragment()
            val args = Bundle()
            args.putSerializable(ARG_PARAM1, param1)
            args.putString(ARG_PARAM2, param2)
            fragment.arguments = args
            return fragment
        }
    }

    fun commit() {
        var weeks = project_plan_week.text.toString()
        var projectId: String? = null

        var weeklyPlanId: String? = null
        if (item !== null) {
            weeklyPlanId = "${item?.projectPlanWeekly?.weeklyPlanId}"
            projectId = "${item?.projectId}"
        } else {
            for (item in mData) {
                if (projectName.equals(item.projectName)) {
                    projectId = "${item.projectId}"
                }
            }
        }
        var writeTime = project_plan_write_time.text.toString()
        var content = project_plan_content.text.toString()
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(activity, "请填写周计划内容!", Toast.LENGTH_SHORT).show()
            return
        }
        if (TextUtils.isEmpty(projectId)) {
            Toast.makeText(activity, "请选择周计划项目!", Toast.LENGTH_SHORT).show()
            return
        }
        dataModel?.projectWeeklyPlanSave(this, weeks, projectId, writeTime, content, weeklyPlanId)
    }

    //公用代码------------------------------
    fun setCommon() {
        if (dataModel === null) {
            dataModel = DataModel()
        }
        val ca = Calendar.getInstance()
        //选择填写时间
        project_plan_write_time.text = String.format("%02d-%02d-%02d", ca.get(Calendar.YEAR), ca.get(Calendar.MONTH) + 1, ca.get(Calendar.DAY_OF_MONTH))
        project_plan_write_time.setOnClickListener {
            val ca = Calendar.getInstance()
            DatePickerDialog(activity, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
                project_plan_write_time.text = String.format("%02d-%02d-%02d", year, month+1, dayOfMonth)
            }, ca.get(Calendar.YEAR), ca.get(Calendar.MONTH), ca.get(Calendar.DAY_OF_MONTH)).show()
        }
    }

    //计划修改-------------------------------
    fun setView() {
        setMySpinner(arrayListOf(item?.projectName))
        project_plan_week.setText("${item?.projectPlanWeekly?.weeks}")
        project_plan_week.isEnabled = false
        project_plan_content.setText(item?.projectPlanWeekly?.context)
        project_plan_write_time.text = item?.projectPlanWeekly?.createTime
        if (item?.reportStatus === null) {
            project_plan_delete.visibility = View.VISIBLE
            project_plan_delete.setOnClickListener {
                delete(item?.projectPlanWeekly?.weeklyPlanId!!)
            }
        } else if (item?.reportStatus?.toInt()!! > 0) {
            fragment_week_plan_detail_title.setRightText("")
            project_plan_write_time.setOnClickListener(null)
            project_plan_content.isEnabled = false
        }
    }

    //新建计划 -----------------------------------------------
    var mData: List<Projects> = ArrayList()
    var projectName: String? = null

    fun creat() {
        dataModel = DataModel()
        dataModel?.getProjects(this)

        //设置周次
        val calendar = Calendar.getInstance()
        calendar.setFirstDayOfWeek(Calendar.MONDAY)
        val curWeekNum = calendar.get(Calendar.WEEK_OF_YEAR)
        project_plan_week.setText("$curWeekNum")
    }

    fun getWeekTimes() {
        val calendar = Calendar.getInstance()
        calendar.setFirstDayOfWeek(Calendar.MONDAY)
        val curWeekNum = calendar.get(Calendar.WEEK_OF_YEAR)
        val rtn = ArrayList<Map<String, String>>()
        val map = HashMap<String, String>()
        map["value"] = Integer.toString(curWeekNum)
        var text = Integer.toString(curWeekNum)
        if (curWeekNum < 10) {
            text = "0$text"
        }
        map["text"] = text
        rtn.add(map)
    }

    fun delete(weekPlanId: Int) {
        if (weekPlanId == 0) {
            Toast.makeText(activity, "请返回列表刷新重试!", Toast.LENGTH_SHORT).show()
            return
        }
        AlertDialog.Builder(activity).setTitle("请确认").setMessage("确认删除本周计划").setNegativeButton("取消", null)
                .setPositiveButton("删除") { dialog, which -> dataModel?.delete(weekPlanId, this@WeekPlanDetailFragment) }.create().show()

    }

}